import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:maihealth/class/login/page/loginPwdPage.dart';
import 'package:maihealth/class/login/provide/loginProvide.dart';
import 'package:maihealth/class/main/webPage.dart';
import 'package:maihealth/utils/constant.dart';
import 'package:maihealth/utils/httpUtils.dart';
import 'package:maihealth/utils/hud.dart';
import 'package:maihealth/utils/router.dart';
import 'package:maihealth/utils/screenUtil.dart';
import 'package:maihealth/utils/toast.dart';
import 'package:provide/provide.dart';

class loginPage extends StatefulWidget {
  @override
  _loginPageState createState() => _loginPageState();
}

class _loginPageState extends State<loginPage> {
TextEditingController editingController = TextEditingController();
FocusNode _focusNode = FocusNode();
bool isFocus = false;
bool isEnable = false;
BuildContext _hudCtx;
@override
  void initState() {
   _focusNode.addListener((){
      setState(() {
        isFocus =  _focusNode.hasFocus;
      });
    });
    //监听文本变化
    editingController.addListener((){
      setState(() {
          isEnable = editingController.text.length>=11;
      });
    });
     super.initState();
  }
  @override
  Widget build(BuildContext context) {
    //配置屏幕缩放工具类
    configScreenUntil(context);
    return ProgressHUD(
      child: Builder(
        builder: (ctx){
            _hudCtx = ctx;
            return Scaffold(
                //避免键盘弹出底部被顶起
                resizeToAvoidBottomPadding: false,
                body:  GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap:(){//点击失去焦点
                      _exitKeyBoard();
                  },
                  child: SafeArea(
                      child: Center(
                        child: Container(
                        padding: EdgeInsets.fromLTRB(setWidth(50), setHeight(100), setWidth(50), setHeight(30)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                              _headerTitle(),
                              _loginTextField(),
                              _line(),
                              _loginBtn(),
                              _yinshiTitle(),
                              _faceLoginBtn()
                          ],
                      ),
                  ))
              ),
          ));
        },
      ),
    );
  }

  //注册登录标题
  Widget _headerTitle() {
    return Text('注册/登录',
        style: TextStyle(fontSize: setFont(25), fontWeight: FontWeight.bold));
  }

  //文本输入框
  Widget _loginTextField() {
    return Container(
      height: setHeight(80),
      padding: EdgeInsets.only(top: setHeight(35)),
      child: CupertinoTextField(
        focusNode: _focusNode,
        controller: editingController,
        keyboardType: TextInputType.number,
        clearButtonMode: OverlayVisibilityMode.editing,
        placeholder: '请输入手机号',
        style: TextStyle(fontSize: setFont(20)),
        decoration: BoxDecoration(
            border: null
        ),
      ),
     ) ;
    }
  //分割线
  Widget _line(){
    return  Divider(color: isFocus ? ThemeColor : ThemeLineColor);
  }
  //登录按钮
  Widget _loginBtn(){
    return Container(
          height: setHeight(48),
          width: setWidth(275),
          margin: EdgeInsets.only(top: setHeight(10)),
          child: RaisedButton(
            onPressed: !isEnable ? null : (){
              print('登录');
              _exitKeyBoard();
              _requestNext();
            },
            child: Text('下一步',style: TextStyle(color: Colors.white),),
            disabledColor: ThemeDisableColor,
            color: ThemeColor,
            shape: StadiumBorder(),
          ),
        );
     }

  //隐私政策
  Widget _yinshiTitle(){
    return Container(
      margin: EdgeInsets.only(top: setHeight(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('登录即代表您同意',style: TextStyle(fontSize: setFont(13))),
          GestureDetector(
            child: Text('隐私政策',style: TextStyle(fontSize: setFont(13),color: ThemeColor)),
              onTap: (){
                String url = HttpUtils.API_PREFIX +'/api/home/privacy/';
                Router.push(context, webPage(url: url));
            },
          ),
          Text('和',style: TextStyle(fontSize: setFont(13))),
          GestureDetector(
            onTap: (){
              String url = HttpUtils.API_PREFIX +'/api/home/term/';
              Router.push(context, webPage(url: url));
            },
            child: Text('服务协议',style: TextStyle(fontSize: setFont(13),color: ThemeColor)),
          ),
        ],
      ),
    );
  }

  //人脸登录按钮
  Widget _faceLoginBtn(){
    return Expanded(child: Container(
      width: setWidth(275),
      alignment: Alignment.bottomCenter,
      child: InkWell(
        onTap: (){
          print('人脸登录');
        },
        child: Image.asset('images/login/login_btn_face.png',width: 86,height: 34),
      )
    )); 
  }

 //退出键盘
 void _exitKeyBoard(){
      //一个小技巧,让他聚焦到下一个不存在的textField,这样键盘就会退出
      FocusScope.of(context).requestFocus(FocusNode());
 }

  //请求下一步
  void _requestNext() async{
    showHud(_hudCtx);
    String tel = editingController.text;
    final provide = Provide.value<loginProvide>(context);
    try {
        await provide.requestUserStatus(tel);
        dismissHud(_hudCtx);
        Router.push(context, loginPwdPage(tel:tel));
    } catch (e) {
        print('error===${e}');
        dismissHud(_hudCtx);
        showToast(e.toString());
    }
  }
}
